package com.yoku.user.dao.redis;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.JedisPool;

/**
 * Desc:
 * Date: 2016/12/14
 */
public class BaseRedisDao<T> {

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    ObjectMapper objectMapper;

    public Boolean setObject(String key, T t){
        try {
            String jsonString = objectMapper.writeValueAsString(t);
            jedisPool.getResource().set(key, jsonString);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }finally {
            jedisPool.close();
        }
        return true;
    }

    public T getByKey(String key){
        try {
            T t = (T) jedisPool.getResource().get(key);
            return t;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }finally {
            jedisPool.close();
        }
    }

    public Boolean delByKey(String key){
        try {
            return jedisPool.getResource().del(key).equals(1);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }finally {
            jedisPool.close();
        }
    }

}
